<template>
  <el-dialog
    v-model="visible"
    :title="isEditing ? '编辑设备' : '添加设备'"
    width="600px"
    :before-close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="100px"
      label-position="left"
    >
      <el-form-item label="设备名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入设备名称" />
      </el-form-item>
      
      <el-form-item v-if="isEditing" label="设备ID">
        <el-input v-model="formData.deviceId" readonly placeholder="系统自动生成" />
      </el-form-item>
      
      <el-form-item label="IP地址" prop="ipAddress">
        <el-input v-model="formData.ipAddress" placeholder="请输入IP地址" />
      </el-form-item>
      
      <el-form-item label="端口" prop="port">
        <el-input-number
          v-model="formData.port"
          :min="1"
          :max="65535"
          placeholder="请输入端口号"
          style="width: 100%"
        />
      </el-form-item>
      
      <el-form-item label="用户名" prop="username">
        <el-input v-model="formData.username" placeholder="请输入用户名" />
      </el-form-item>
      
      <el-form-item label="密码" prop="password">
        <el-input
          v-model="formData.password"
          type="password"
          placeholder="请输入密码"
          show-password
        />
      </el-form-item>
      
      <el-form-item label="制造商" prop="manufacturer">
        <el-select
          v-model="formData.manufacturer"
          placeholder="请选择制造商"
          style="width: 100%"
          filterable
          allow-create
        >
          <el-option
            v-for="manufacturer in manufacturers"
            :key="manufacturer"
            :label="manufacturer"
            :value="manufacturer"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="型号" prop="model">
        <el-input v-model="formData.model" placeholder="请输入设备型号" />
      </el-form-item>
      
      <el-form-item label="启用状态" prop="enabled">
        <el-switch v-model="formData.enabled" />
      </el-form-item>
      
      <el-form-item label="描述" prop="description">
        <el-input
          v-model="formData.description"
          type="textarea"
          :rows="3"
          placeholder="请输入设备描述"
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          {{ isEditing ? '更新' : '添加' }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { MANUFACTURERS } from '@/utils/constants'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  device: {
    type: Object,
    default: () => ({})
  },
  isEditing: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue', 'submit', 'cancel'])

const formRef = ref()
const loading = ref(false)

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const manufacturers = computed(() => MANUFACTURERS)

const formData = reactive({
  name: '',
  ipAddress: '',
  port: 80,
  username: 'admin',
  password: '',
  manufacturer: '',
  model: '',
  enabled: true,
  description: ''
})

const rules = {
  name: [
    { required: true, message: '请输入设备名称', trigger: 'blur' },
    { min: 2, max: 50, message: '设备名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  ipAddress: [
    { required: true, message: '请输入IP地址', trigger: 'blur' },
    {
      pattern: /^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
      message: '请输入正确的IP地址格式',
      trigger: 'blur'
    }
  ],
  port: [
    { required: true, message: '请输入端口号', trigger: 'blur' },
    { type: 'number', min: 1, max: 65535, message: '端口号范围为 1-65535', trigger: 'blur' }
  ],
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  manufacturer: [
    { required: true, message: '请选择制造商', trigger: 'change' }
  ]
}

// 监听设备数据变化，更新表单
watch(
  () => props.device,
  (newDevice) => {
    if (newDevice && props.isEditing) {
      Object.assign(formData, {
        name: newDevice.name || '',
        ipAddress: newDevice.ipAddress || '',
        port: newDevice.port || 80,
        username: newDevice.username || 'admin',
        password: newDevice.password || '',
        manufacturer: newDevice.manufacturer || '',
        model: newDevice.model || '',
        enabled: newDevice.enabled !== undefined ? newDevice.enabled : true,
        description: newDevice.description || ''
      })
    }
  },
  { immediate: true, deep: true }
)

// 监听对话框显示状态
watch(visible, (newVisible) => {
  if (newVisible) {
    nextTick(() => {
      formRef.value?.clearValidate()
    })
    
    if (!props.isEditing) {
      // 重置表单为默认值
      Object.assign(formData, {
        name: '',
        ipAddress: '',
        port: 80,
        username: 'admin',
        password: '',
        manufacturer: '',
        model: '',
        enabled: true,
        description: ''
      })
    }
  }
})

const handleClose = () => {
  visible.value = false
  emit('cancel')
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    loading.value = true
    
    const deviceData = { ...formData }
    if (props.isEditing && props.device?.id) {
      deviceData.id = props.device.id
    }
    
    emit('submit', deviceData)
    
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>